package io.webfolder.cdp.channel;

import java.net.URI;
import java.net.URISyntaxException;

import io.webfolder.cdp.exception.CdpException;
import io.webfolder.cdp.session.MessageHandler;
import io.webfolder.cdp.session.SessionFactory;

public class TooTallNateWebSocketFactory implements ChannelFactory, AutoCloseable {

	private TooTallNateWebSocketListener webSocket;

	@Override
	public Channel createChannel(Connection connection, SessionFactory factory, MessageHandler handler) {
		if (webSocket != null) {
			throw new IllegalStateException();
		}
		String url = ((WebSocketConnection) connection).getUrl();
		URI uri;
		try {
			uri = new URI(url);
		} catch (URISyntaxException e) {
			throw new CdpException(e);
		}
		webSocket = new TooTallNateWebSocketListener(uri, factory, handler);
		TooTallNateWebSocketChannel channel = new TooTallNateWebSocketChannel(webSocket);
		return channel;
	}

	@Override
	public void close() {
		if (webSocket != null && webSocket.isOpen()) {
			webSocket.close();
		}
	}
}
